﻿/*
 * GNU GENERAL PUBLIC LICENSE v2
 * 
 * Developers: Alan Audette, Oguz Bastemur
 */
namespace SqlDatabaseBackup.Tools
{
    using System;
    using System.Collections.Generic;
    using System.Net.Mail;

    using SqlDatabaseBackup.Helper;

    internal static class Mail
    {
        internal static bool SendEmail()
        {
            try
            {
                if (Program.configuration.Email.SendOn == Configuration.Email.SendRules.Never) return true;

                if (Program.configuration.Email.SendOn == Configuration.Email.SendRules.OnFail && !Program.processFailed) return true;

                if (Program.configuration.Email.SendOn == Configuration.Email.SendRules.OnSuccess
                    && Program.processFailed) return true;

                string[] reps = Program.configuration.Email.Receipents.Trim().Split(';');
                if (reps.Length == 0)
                    throw new Exception("No Email Receipent Defined");

                MailAddress toAdr = new MailAddress(reps[0]);
                using (MailMessage mess = new MailMessage(new MailAddress(Program.configuration.Email.Sender, "SQLDatabaseBackup Notification"), toAdr))
                {
                    if (reps.Length > 1)
                    {
                        for (int i = 1; i < reps.Length; i++)
                        {
                            if (reps[i] != "")
                            {
                                mess.To.Add(new MailAddress(reps[i]));
                            }
                        }
                    }

                    mess.Body = @"
<!DOCTYPE html>
<html>
    <head>
        <style>
            .fnormal:{font:normal normal 12px Arial;}
        </style>
    </head>
    <body>
        "+ToConsole.htmlLog.ToString()+@"
    </body>
</html>
";
                    mess.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient();
                    client.Port = Program.configuration.Email.SMTPPort;
                    client.Host = Program.configuration.Email.SMTPHost;
                    client.Credentials = new System.Net.NetworkCredential(Program.configuration.Email.Username, Program.configuration.Email.Password);
                    client.Send(mess);

                }
            }catch(Exception e)
            {
                Log.Message("Email Failed :"+ e.Message, System.Diagnostics.EventLogEntryType.Error);
                Program.processFailed = true;
                return false;
            }

            Log.Message("Email Sent ", System.Diagnostics.EventLogEntryType.SuccessAudit);
            return true;
        }
    }
}